package com.aimashi.service.impl;

import com.aimashi.common.ErrorCode;
import com.aimashi.constant.CommonConstant;
import com.aimashi.exception.BusinessException;
import com.aimashi.judge.JudgeService;
import com.aimashi.model.dto.questionsubmit.QuestionSubmitAddRequest;
import com.aimashi.model.dto.questionsubmit.QuestionSubmitQueryRequest;
import com.aimashi.model.entity.Question;
import com.aimashi.model.entity.QuestionSubmit;
import com.aimashi.model.entity.User;
import com.aimashi.model.enums.QuestionSubmitLanguageEnum;
import com.aimashi.model.enums.QuestionSubmitStatusEnum;
import com.aimashi.model.vo.QuestionSubmitVO;
import com.aimashi.service.QuestionService;
import com.aimashi.service.QuestionSubmitService;
import com.aimashi.service.UserService;
import com.aimashi.utils.SqlUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.aimashi.mapper.QuestionSubmitMapper;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

/**
* @author xiafuyou
* @description 针对表【question_submit(题目提交)】的数据库操作Service实现
* @createDate 2024-10-06 00:10:15
*/
@Service
public class QuestionSubmitServiceImpl extends ServiceImpl<QuestionSubmitMapper, QuestionSubmit>
    implements QuestionSubmitService{

    @Resource
    private QuestionService questionService;

    @Resource
    private UserService userService;

    @Resource
    @Lazy
    private JudgeService judgeService;

    /**
     * 题目提交
     *
     * @param questionSubmitAddRequest
     * @param loginUser
     * @return
     */
    @Override
    public long doQuestionSubmit(QuestionSubmitAddRequest questionSubmitAddRequest, User loginUser) {
        String language = questionSubmitAddRequest.getLanguage();
        QuestionSubmitLanguageEnum languageEnum = QuestionSubmitLanguageEnum.getEnumByValue(language);
        if (languageEnum == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"编程语言错误");
        }
        long questionId = questionSubmitAddRequest.getQuestionId();
        // 判断实体是否存在，根据类别获取实体
        Question question = questionService.getById(questionId);
        System.out.println(question);
        if (question == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        // 是否已提交题目
        long userId = loginUser.getId();
        // 每个用户串行提交题目
        QuestionSubmit questionSubmit = new QuestionSubmit();
        questionSubmit.setUserId(userId);
        questionSubmit.setQuestionId(questionId);
        questionSubmit.setCode(questionSubmitAddRequest.getCode());
        questionSubmit.setLanguage(language);
        // 设置初始状态
        questionSubmit.setStatus(QuestionSubmitStatusEnum.WAITING.getValue());
        questionSubmit.setJudgeInfo("{}");
        boolean save = this.save(questionSubmit);
        if (!save){
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "数据插入失败");
        }
        Long questionSubmitId = questionSubmit.getId();
        CompletableFuture.runAsync(() ->{
            judgeService.doJudge(questionSubmitId);
        });
        return questionSubmitId;
    }

    /**
     * 根据查询请求构建查询包装器
     * 此方法用于根据用户请求中的条件，构建一个查询包装器，以便后续根据这些条件过滤数据
     * @param questionSubmitQueryRequest 用户提交的问题查询请求，包含过滤和排序条件
     * @return 返回构建的查询包装器，用于后续的数据查询
     */
    @Override
    public QueryWrapper<QuestionSubmit> getQueryWrapper(QuestionSubmitQueryRequest questionSubmitQueryRequest) {
        // 初始化查询包装器
        QueryWrapper<QuestionSubmit> queryWrapper = new QueryWrapper<>();
        // 如果查询请求为空，则直接返回空的查询包装器
        if (questionSubmitQueryRequest == null)
            return queryWrapper;

        // 从查询请求中获取各个查询条件
        String language = questionSubmitQueryRequest.getLanguage();
        Integer status = questionSubmitQueryRequest.getStatus();
        Long userId = questionSubmitQueryRequest.getUserId();
        Long questionId = questionSubmitQueryRequest.getQuestionId();
        String sortField = questionSubmitQueryRequest.getSortField();
        String sortOrder = questionSubmitQueryRequest.getSortOrder();

        // 拼接查询条件
        // 根据语言查询，如果语言不为空
        queryWrapper.eq(StringUtils.isNotBlank(language),"language",language);
        // 根据用户ID查询，如果用户ID不为空
        queryWrapper.eq(ObjectUtils.isNotEmpty(userId),"userId",userId);
        // 根据问题ID查询，如果问题ID不为空
        queryWrapper.eq(ObjectUtils.isNotEmpty(questionId),"questionId",questionId);
        // 根据状态查询，如果状态有效
        queryWrapper.eq(QuestionSubmitStatusEnum.getEnumByValue(String.valueOf(status)) != null,"status",status);
        // 只查询未删除的数据
        queryWrapper.eq("isDelete",false);

        // 根据有效的排序字段和排序顺序进行排序
        queryWrapper.orderBy(SqlUtils.validSortField(sortField),sortOrder.equals(CommonConstant.SORT_ORDER_ASC), sortField);

        // 返回构建好的查询包装器
        return queryWrapper;
    }


    /**
     * 根据问题提交对象和当前用户获取问题提交的VO（Value Object）
     * 此方法主要用于转换问题提交实体到问题提交值对象，并根据当前用户权限决定是否返回问题代码
     *
     * @param questionSubmit 问题提交实体对象
     * @param loginUser 当前登录用户对象
     * @return 返回转换后的问题提交值对象，其中可能不包含问题代码
     */
    @Override
    public QuestionSubmitVO getQuestionSubmitVO(QuestionSubmit questionSubmit, User loginUser) {
        // 将问题提交实体对象转换为问题提交值对象
        QuestionSubmitVO questionSubmitVO = QuestionSubmitVO.objToVo(questionSubmit);

        // 获取当前登录用户ID
        long userId = loginUser.getId();

        // 判断当前登录用户是否是提交问题的用户，如果不是且当前用户不是管理员，则不返回问题代码
        if (userId != questionSubmit.getUserId() && !userService.isAdmin(loginUser)){
            questionSubmitVO.setCode(null);
        }

        // 返回问题提交值对象
        return questionSubmitVO;
    }


    /**
     * 获取问题提交的分页数据转换为VO(Page<QuestionSubmitVO>)
     * 此方法用于将数据库查询出的问题提交分页数据(Page<QuestionSubmit>)转换为用于前端展示的VO分页数据(Page<QuestionSubmitVO>)
     * 主要涉及到对每个问题提交记录的转换，以及分页信息的保留
     *
     * @param questionSubmitPage 问题提交的分页数据，包含多条问题提交记录
     * @param loginUser 登录用户信息，用于在转换过程中获取用户相关数据
     * @return 返回转换后的QuestionSubmitVO分页数据，包含同样的分页和数据记录
     */
    @Override
    public Page<QuestionSubmitVO> getQuestionSubmitVOPage(Page<QuestionSubmit> questionSubmitPage, User loginUser) {
        // 获取问题提交分页数据中的记录列表
        List<QuestionSubmit> questionSubmitList = questionSubmitPage.getRecords();
        // 初始化新的VO分页数据对象，保留原有的分页信息
        Page<QuestionSubmitVO> questionSubmitVOPage = new Page<>(questionSubmitPage.getCurrent(),
                questionSubmitPage.getSize(), questionSubmitPage.getTotal());
        // 如果记录列表为空，则直接返回空的VO分页数据对象
        if (CollectionUtils.isEmpty(questionSubmitList)){
            return questionSubmitVOPage;
        }
        // 遍历问题提交记录列表，将其一一转换为VO对象，并收集为一个新的列表
        List<QuestionSubmitVO> questionSubmitVOList = questionSubmitList.stream()
                .map(questionSubmit -> getQuestionSubmitVO(questionSubmit, loginUser))
                .collect(Collectors.toList());
        // 将转换后的记录列表设置到VO分页数据对象中
        questionSubmitVOPage.setRecords(questionSubmitVOList);
        // 返回转换后的VO分页数据对象
        return questionSubmitVOPage;
    }



}




